package models

import (
	"godemo/dao"
	"time"
)

type User struct {
	Id         int       `json:"id"`
	Name       string    `json:"name"`
	Password   string    `json:"password"`
	CreateTime time.Time `json:"create_time"`
	UpdateTime time.Time `json:"update_time"`
}

func (User) TableName() string {
	return "user"
}

func GetUserTest(id int) (User, error) {
	var user User
	err := dao.Db.Where("id=?", id).First(&user).Error
	return user, err
}

func AddUser(name string) (int, error) {
	user := User{Name: name}
	err := dao.Db.Create(&user).Error
	return user.Id, err
}

func UpdateUser(id int, name string) {
	dao.Db.Model(&User{}).Where("id=?", id).Update("name", name)
}

func DeleteUser(id int) error {
	err := dao.Db.Where("id=?", id).Delete(&User{}).Error
	return err
}

func GetUserList() ([]User, error) {
	var users []User
	err := dao.Db.Where("id < ?", 10).Find(&users).Error
	return users, err
}

func FindUserByName(name string) (User, error) {
	var user User
	err := dao.Db.Where("name = ?", name).First(&user).Error
	return user, err
}

func SaveUser(name string, pwd string) (int, error) {
	user := User{Name: name, Password: pwd, CreateTime: time.Now(), UpdateTime: time.Now()}
	err := dao.Db.Save(&user).Error
	return user.Id, err
}
